/**
 * 
 */

jQuery(function($){

	var sacButtons;

	if ( wgAction == "formedit"	|| wgCanonicalSpecialPageName == "FormEdit" ) {

		// only bind to submit event is form is displayed in topmost frame
		// float forms break otherwise
		if (top.location == location) {
			$('#sfForm').bind( "submit", handleSubmit );
		}

		sacButtons = $('.directedit-save_and_continue');
		sacButtons.click( handleSaveAndContinue);

		$('input,select,textarea')

		.live( "keypress", function ( event ) {
			if ( event.which == 0 ) return true;
			return setChanged( event );
		})
		.live( "change", setChanged );

		$('.multipleTemplateAdder,.remover,.rearrangerImage')
		.live( "click", setChanged );

		$('.rearrangerImage')
		.live( "mousedown", setChanged );

	}

	function setChanged() {

		sacButtons.removeAttr("disabled");

		sacButtons
		.addClass("directedit-save_and_continue-changed");

		return true;
	}

	function handleSubmit( event ) {

		// remove old error messages
		var el = document.getElementById("form_error_header");
		if (el) el.parentNode.removeChild(el);

		var saveButton = $('#wpSave');

		if (validateAll()) {
			saveButton.attr("disabled", "disabled");

			sajax_request_type = 'POST';

			sajax_do_call( 'DirectEdit::handleSubmit', collectData( $(this) ), function( ajaxHeader ){

				saveButton.removeAttr("disabled");
				if ( ajaxHeader.status == 200 ) {
					window.location = ajaxHeader.getResponseHeader("X-Location");
				} else {
					// FIXME: This does not work, 'this' is not the form
					this.submit();  // use old handler as fallback
				}
			} );
		}

		return false;
	}

	function handleSaveAndContinue( event ) {

		// remove old error messages
		var el = document.getElementById("form_error_header");

		if (el) el.parentNode.removeChild(el);
		
		if (validateAll()) {
			sacButtons.attr("disabled", "disabled");

			sacButtons
			.addClass("directedit-save_and_continue-wait")
			.removeClass("directedit-save_and_continue-changed");
			
			sajax_request_type = 'POST';
			var form = $('#sfForm');

			sajax_do_call( 'DirectEdit::handleSubmit', collectData( form ), function( ajaxHeader ){

				if ( ajaxHeader.status == 200 ) {

					var target = form.find('input[name="target"]');

					if ( target.length == 0 ) {

						target = jQuery('<input type="hidden" name="target">');

						form.append (target);
					}

					target.attr( 'value', ajaxHeader.getResponseHeader("X-Target") );

					sacButtons
					.addClass("directedit-save_and_continue-ok")
					.removeClass("directedit-save_and_continue-wait")
					.removeClass("directedit-save_and_continue-error");

				} else {

					sacButtons
					.addClass("directedit-save_and_continue-error")
					.removeClass("directedit-save_and_continue-wait");
					
				}

			} );
		}

		return false;
	}

	function collectData( form ) {

		var params = form.serialize();

		if (wgAction == "formedit") {
			params += "&target=" + encodeURIComponent( wgPageName );
		} else if ( wgCanonicalSpecialPageName == "FormEdit") {

			var url = String(window.location);

			var stop = url.indexOf("?");
			if ( stop > 0 ) url = url.substring(0, stop);

			var start = url.indexOf( wgPageName ) + String(wgPageName).length + 1;
			stop = url.indexOf("/", start);

			if (stop >= 0) {
				params += "&form=" + encodeURIComponent( url.substring(start, stop) );

				start = stop + 1;
				params += "&target=" + encodeURIComponent( url.substr(start) );

			} else {
				params += "&form=" + encodeURIComponent( url.substr(start) );
			}

		}

		var data = new Array();
		data.push( params );

		return data;
	}

})
